<?php
// +----------------------------------------------------------------------
// | 基础类
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app;

use think\Model;

/**
 * 应用请求对象类
 *
 * Class Request
 * @package app
 */
class Request extends \think\Request
{

    /**
     * 设置当前用户信息
     * 
     * @return
     */
    public function setUser(Model $user): void
    {
        $this->user_id = $user->id;
        $this->userInfo = $user->toArray();
    }

    /**
     * 获取已登录的用户ID
     * 
     * @return
     */
    public function getUserId(): int
    {
        return $this->user_id ?? 0;
    }

    /**
     * 获取已登录的用户完整信息
     * 
     * @return
     */
    public function getUserInfo(): array
    {
        return $this->userInfo ?? [];
    }

    /**
     * 获取已登录的用户角色
     * 
     * @return
     */
    public function getUserRoles(): array
    {
        $roles = [];
        if (!empty($this->userInfo['roles'])) {
            foreach ($this->userInfo['roles'] as $role) {
                $roles[] = $role['code'];
            }
        }
        return $roles;
    }

    /**
     * 获取已登录的用户权限
     * 
     * @return
     */
    public function getUserPermissions(): array
    {
        $permissions = [];
        if (!empty($this->userInfo['roles'])) {
            foreach ($this->userInfo['roles'] as $role) {
                if (is_array($role['permissions'])) {
                    $permissions = array_merge($permissions, $role['permissions']);
                }
            }
        }
        return $permissions;
    }
}
